package com.hao.epidemic_prevention.controller;

import com.alibaba.fastjson.JSONObject;
import com.hao.epidemic_prevention.bean.*;
import com.hao.epidemic_prevention.security.adminlogin.AdminServiceImpl;
import com.hao.epidemic_prevention.service.AdminService;
import com.hao.epidemic_prevention.service.DepartmentService;
import com.hao.epidemic_prevention.service.UserService;
import com.hao.epidemic_prevention.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminServiceImpl adminServiceImpl;
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;

    private static double [] temperatureRange = new double[]{36, 36.7, 37.3};

    private Logger logger = LoggerFactory.getLogger(getClass());

    public Integer getPage(QueryTodayCondition condition) {
        Integer result = 0;

        Integer page = condition.getPage();
        Integer pageLimit = condition.getPageLimit();
        Integer userRecordTodayNum = userService.getUserRecordNumToday();

        if(page <= 0){
            result = 1;

            return result;
        }
        else if((page-1)*pageLimit >= userRecordTodayNum) {

            result = 2;
            return result;
        }


        return result;
    }

    @RequestMapping("/loginFail")
    public JSONResult loginFail() {

        return JSONResult.build(500, "登录失败", null);
    }

    @RequestMapping("/loginSuccess")
    public JSONResult loginSuccess() {
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("Username", principal.getUsername());
        map.put("Granted Authorities", principal.getAuthorities().toString());

        return JSONResult.build(200, "登录成功", map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public void login(@RequestBody Admin admin) {
        UserDetails result = adminServiceImpl.loadUserByUsername(admin.getUsername());
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {//清除认证
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }

        //return JSONResult.build(200, "登出成功", null);
    }

    @RequestMapping("/toLogin")
    public void toLogin() {
        logger.info("登录请求");
        //return JSONResult.build(200, "登出成功", null);
    }


//    @RequestMapping("/getUserRecordToday")
//    public JSONResult getUserRecordToday(@RequestBody QueryCondition condition) {
//
//
//        if(condition.getPage() == null || condition.getPageLimit() == null) {
//            return new JSONResult(201, "查询失败，page和pageLimit不能为空", null);
//        }
//
//        List<UserRecord> result = userService.getUserRecordToday10(condition);
//
//
//        Integer pageInfo = getPage(condition);
//
//        if(pageInfo ==  1){
//            return new JSONResult(202, "查询失败，page页数错误", null);
//        }
//        else if(pageInfo == 2) {
//            return new JSONResult(203, "查询失败，该页为空", null);
//        }
//        else{
//            return new JSONResult(200, "查询成功", result);
//        }
//    }

    @RequestMapping("/getUserRecordToday")
    public JSONResult getUserRecordToday(@RequestBody QueryTodayCondition condition) {
        if(condition.getSortWay() == null || condition.getSortWay().equals("")) {
            return new JSONResult(201, "查询失败，sortWay不能为空", null);
        }

        List<UserRecord> list = null;
        if(condition.getSortWay().equals("正常")) {
            list = userService.getUserRecordToday(condition);
            return new JSONResult(200, "查询成功", list);
        }
        else if(condition.getSortWay().equals("按体温排序")) {
            if(condition.getSortMethod() == null || condition.getSortMethod().equals("")) {
                return new JSONResult(202, "查询失败，sortMethod不能为空", null);
            }
            else if(condition.getSortMethod().equals("正序")) {
                list = userService.getUserRecordTodayWithTAsc(condition);
                return new JSONResult(200, "查询成功", list);
            }
            else if(condition.getSortMethod().equals("倒序")) {
                list = userService.getUserRecordTodayWithTDesc(condition);
                return new JSONResult(200, "查询成功", list);
            }
        }

        return new JSONResult(203, "查询失败，sortWay格式错误", null);
    }

    @RequestMapping("/getNotReportUserToday")
    public JSONResult getNotReportUserToday(@RequestBody QueryRangeCondition condition) {
        List<User> list = userService.getNotReportUserToday(condition);
        return new JSONResult(200, "查询成功", list);
    }

    @RequestMapping("/getUserRecordRange")
    public JSONResult getUserRecordRange(@RequestBody QueryRangeCondition condition) {
        if(condition.getSortWay() == null || condition.getSortWay().equals("")) {
            condition.setSortWay("按时间排序");
        }
        if(condition.getSortMethod() == null || condition.getSortMethod().equals("")) {
            condition.setSortMethod("正序");
        }

        if(condition.getStartTime() == null || condition.getStartTime().equals("") ||
                condition.getEndTime() == null || condition.getEndTime().equals("")) {
            return new JSONResult(204, "查询失败，时间范围不齐", null);
        }

        //System.out.println(condition.getSortWay());

        List<UserRecord> list = null;
        if(condition.getSortWay().equals("按时间排序")) {
            if(condition.getSortMethod().equals("正序")) {
                list = userService.getUserRecordRangeWithDAsc(condition);
                return new JSONResult(200, "查询成功", list);
            }
            else if(condition.getSortMethod().equals("倒序")) {
                list = userService.getUserRecordRangeWithDDesc(condition);
                return new JSONResult(200, "查询成功", list);
            }


        }
        else if(condition.getSortWay().equals("按体温排序")) {

            if(condition.getSortMethod().equals("正序")) {
                list = userService.getUserRecordRangeWithTAsc(condition);
                return new JSONResult(200, "查询成功", list);
            }
            else if(condition.getSortMethod().equals("倒序")) {
                list = userService.getUserRecordRangeWithTDesc(condition);
                return new JSONResult(200, "查询成功", list);
            }
//            if(condition.getSortMethod() == null || condition.getSortMethod().equals("")) {
//                return new JSONResult(202, "查询失败，sortMethod不能为空", null);
//            }
//            else if(condition.getSortMethod().equals("正序")) {
//                list = userService.getUserRecordRangeWithTAsc(condition);
//                return new JSONResult(200, "查询成功", list);
//            }
//            else if(condition.getSortMethod().equals("倒序")) {
//                list = userService.getUserRecordRangeWithTDesc(condition);
//                return new JSONResult(200, "查询成功", list);
//            }
        }

        return new JSONResult(203, "查询失败，sortWay或sortMethod格式错误", null);
    }

    @RequestMapping("/getTAnalysis")
    public JSONResult getTAnalysis(@RequestBody QueryRangeCondition condition) {
        if(condition.getStartTime() == null || condition.getStartTime().equals("") ||
                condition.getEndTime() == null || condition.getEndTime().equals("")) {
            return new JSONResult(204, "查询失败，时间范围不齐", null);
        }

        List<UserRecord> list = null;
        list = userService.getUserRecordRangeWithDAsc(condition);
        int [] temperatureRangeNum = new int[temperatureRange.length + 1];

        for(int i = 0 ; i < list.size(); i ++){
            if(list.get(i).getTemperature() < temperatureRange[0]) {
                temperatureRangeNum[0] ++;
            }
            else if(list.get(i).getTemperature() >= temperatureRange[0]
                    && list.get(i).getTemperature() < temperatureRange[1]) {
                temperatureRangeNum[1] ++;
            }
            else if(list.get(i).getTemperature() >= temperatureRange[1]
                    && list.get(i).getTemperature() < temperatureRange[2]) {
                temperatureRangeNum[2] ++;
            }
            else if(list.get(i).getTemperature() >= temperatureRange[2]) {
                temperatureRangeNum[3] ++;
            }
        }
//        JsonObject result = new JsonObject();
//        JsonObject item = new JsonObject();
//        JsonArray data = new JsonArray();
//
//        item.addProperty("小于36", temperatureRangeNum[0]);
//        item.addProperty("[36,36.7)", temperatureRangeNum[1]);
//        item.addProperty("[36.7,37.3)", temperatureRangeNum[2]);
//        item.addProperty("大于等于37.3", temperatureRangeNum[3]);
//
//        data.add(item);
//
//        result.addProperty("status", 200);
//        result.addProperty("msg", "查询成功");
//        result.add("data", data);
//
//
//        System.out.println(result);
//
//        return result;

        JSONObject result = new JSONObject();
        result.put("name", "<36°C");
        result.put("value", temperatureRangeNum[0]);

        JSONObject result2 = new JSONObject();
        result2.put("name", "[36°C,36.7°C)");
        result2.put("value", temperatureRangeNum[1]);

        JSONObject result3 = new JSONObject();
        result3.put("name", "[36.7°C,37.3°C)");
        result3.put("value", temperatureRangeNum[2]);

        JSONObject result4 = new JSONObject();
        result4.put("name", ">=37.3°C");
        result4.put("value", temperatureRangeNum[3]);

        //System.out.println(result);

        List<JSONObject> resultList = new ArrayList<>();
        resultList.add(result);
        resultList.add(result2);
        resultList.add(result3);
        resultList.add(result4);

        return new JSONResult(200, "查询成功", resultList);
//        Map<String, Integer> result = new HashMap<>();
//
//        result.put("<36°C", temperatureRangeNum[0]);
//        result.put("[36°C,36.7°C)", temperatureRangeNum[1]);
//        result.put("[36.7°C,37.3°C)", temperatureRangeNum[2]);
//        result.put(">=37.3°C", temperatureRangeNum[3]);
//
//
//        return new JSONResult(200, "查询成功", result);
    }

    @RequestMapping("/getDepartmentAnalysis")
    public JSONResult getDepartmentAnalysis(@RequestBody QueryRangeCondition condition) {
        if(condition.getStartTime() == null || condition.getStartTime().equals("") ||
                condition.getEndTime() == null || condition.getEndTime().equals("")) {
            return new JSONResult(204, "查询失败，时间范围不齐", null);
        }
        if(condition.getRole() == null || condition.getRole().equals("")) {
            condition.setRole("Student");
        }

        List<Department> departmentList = departmentService.getAllDepartment();
        List<JSONObject> result = new ArrayList<>();

        for(int i = 0; i < departmentList.size(); i ++) {
            condition.setDepartmentName(departmentList.get(i).getDepartmentName());

            Integer userNum = userService.getUserNum(condition);
            List<User> notRepoetUser = userService.getNotReportUserToday(condition);
            Integer notRepoetNum = notRepoetUser.size();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("role", condition.getRole());
            jsonObject.put("departmentName", condition.getDepartmentName());
            jsonObject.put("userNum", userNum);
            jsonObject.put("notRepoetNum", notRepoetNum);
            jsonObject.put("未打卡率", (double)notRepoetNum/userNum * 100 + "%");
            //System.out.println(result);

            result.add(jsonObject);
        }



        return new JSONResult(200, "查询成功", result);

    }

    @RequestMapping("/getAllUser")
    public JSONResult getAllUser() {
        List<User> list = userService.getAllUser();
        return new JSONResult(200, "查询成功", list);
    }

    @RequestMapping("/freezeUser")
    public JSONResult freezeUser(@RequestParam String userId) {
        Boolean result = userService.freezeUser(userId);
        if(result) {
            return new JSONResult(200, "冻结账号成功", result);
        }
        else {
            return new JSONResult(500, "冻结账号失败", result);
        }
    }

    @RequestMapping("/unfreezeUser")
    public JSONResult unfreezeUser(@RequestParam String userId) {
        Boolean result = userService.unfreezeUser(userId);
        if(result) {
            return new JSONResult(200, "解冻账号成功", result);
        }
        else {
            return new JSONResult(500, "解冻账号失败", result);
        }
    }
}
